﻿using System.Security.Cryptography;

namespace WidgetsDesign.API.Helper
{
    public class AESHelper
    {
        public static class EncryptUtil
        {
            /// <summary>
            /// 加密
            /// </summary>
            /// <param name="text"></param>
            /// <param name="key"></param>
            /// <param name="iv"></param>
            /// <returns></returns>
            public static string EncryptAES(string text, string key, string iv)
            {
                var sourceBytes = System.Text.Encoding.UTF8.GetBytes(text);
                var aes = System.Security.Cryptography.Aes.Create();
                aes.Mode = System.Security.Cryptography.CipherMode.CBC;
                aes.Padding = System.Security.Cryptography.PaddingMode.PKCS7;
                aes.Key = System.Text.Encoding.UTF8.GetBytes(key);
                aes.IV = System.Text.Encoding.UTF8.GetBytes(iv);
                var transform = aes.CreateEncryptor();
                return System.Convert.ToHexString(transform.TransformFinalBlock(sourceBytes, 0, sourceBytes.Length));
            }
            /// <summary>
            /// 解密
            /// </summary>
            /// <param name="text"></param>
            /// <param name="key"></param>
            /// <param name="iv"></param>
            /// <returns></returns>
            public static string DecryptAES(string text, string key, string iv)
            {
                try
                {
                    var encryptBytes = System.Convert.FromHexString(text);
                    var aes = System.Security.Cryptography.Aes.Create();
                    aes.Mode = System.Security.Cryptography.CipherMode.CBC;
                    aes.Padding = System.Security.Cryptography.PaddingMode.PKCS7;
                    aes.Key = System.Text.Encoding.UTF8.GetBytes(key);
                    aes.IV = System.Text.Encoding.UTF8.GetBytes(iv);
                    var transform = aes.CreateDecryptor();
                    return System.Text.Encoding.UTF8.GetString(transform.TransformFinalBlock(encryptBytes, 0, encryptBytes.Length));
                }
                catch (Exception)
                {
                    return "";
                }
            }
        }

    }
}